package com.zzyl.nursing.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.aliyun.iot20180120.Client;
import com.aliyun.iot20180120.models.*;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.core.domain.AjaxResult;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.framework.config.properties.AliIoTConfigProperties;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.vo.DeviceVo;
import com.zzyl.nursing.vo.ProductVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.service.IDeviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import static com.zzyl.common.constant.CacheConstants.IOT_PROJECT_LIST;

/**
 * 设备Service业务层处理
 *
 * @author rouiqasy
 * @date 2025-01-10
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService {
    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private Client client;

    @Autowired
    private AliIoTConfigProperties aliIoTConfigProperties;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 查询设备
     *
     * @param id 设备主键
     * @return 设备
     */
    @Override
    public Device selectDeviceById(Long id) {
        return deviceMapper.selectById(id);
    }

    /**
     * 查询设备列表
     *
     * @param device 设备
     * @return 设备
     */
    @Override
    public List<Device> selectDeviceList(Device device) {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 新增设备
     *
     * @param device 设备
     * @return 结果
     */
    @Override
    public int insertDevice(Device device) {
        return deviceMapper.insert(device);
    }

    /**
     * 修改设备
     *
     * @param device 设备
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int updateDevice(Device device) {
        int result = deviceMapper.updateById(device);
        BatchUpdateDeviceNicknameRequest request = new BatchUpdateDeviceNicknameRequest();

        //添加数据
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        BatchUpdateDeviceNicknameResponse response;
        List<BatchUpdateDeviceNicknameRequest.BatchUpdateDeviceNicknameRequestDeviceNicknameInfo> nicknameInfos = new ArrayList<>();
        BatchUpdateDeviceNicknameRequest.BatchUpdateDeviceNicknameRequestDeviceNicknameInfo nicknameInfo = new BatchUpdateDeviceNicknameRequest.BatchUpdateDeviceNicknameRequestDeviceNicknameInfo();
        nicknameInfo.setDeviceName(device.getDeviceName());
        nicknameInfo.setNickname(device.getNickname());
        nicknameInfo.setProductKey(device.getProductKey());

        nicknameInfos.add(nicknameInfo);
        request.setDeviceNicknameInfo(nicknameInfos);

        try {
            response = client.batchUpdateDeviceNickname(request);
        } catch (Exception e) {
            throw new RuntimeException("修改设备失败");
        }

        if (!response.getBody().success){
            throw new RuntimeException("修改设备失败");
        }

        return result;
    }

    /**
     * 批量删除设备
     *
     * @param ids 需要删除的设备主键
     * @return 结果
     */
    @Override
    public int deleteDeviceByIds(Long[] ids) {
        return deviceMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除设备信息
     *
     * @param id 设备主键
     * @return 结果
     */
    @Override
    public int deleteDeviceById(Long id) {
        return deviceMapper.deleteById(id);
    }

    /**
     * 同步产品列表
     */
    @Override
    public void syncProductList() {
        //请求参数
        QueryProductListRequest request = new QueryProductListRequest();
        request.setCurrentPage(1);
        request.setPageSize(100);
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        //从IOT平台获取产品列表
        QueryProductListResponse response;
        try {
            response = client.queryProductList(request);
        } catch (Exception e) {
            throw new RuntimeException("同步产品列表失败");
        }

        //判断产品列表是否为空
        if (!response.getBody().getSuccess()) {
            throw new RuntimeException("调用产品列表失败");
        }
        //将产品列表存到Redis中
        redisTemplate.opsForValue().set(IOT_PROJECT_LIST, JSON.toJSONString(response.body.data.list.getProductInfo()));

    }

    /**
     * 从缓存中获取产品列表
     *
     * @return 产品列表
     */
    @Override
    public List<ProductVo> getAllProduct() {
        //从Redis缓存中获取所有产品
        String productListStr = redisTemplate.opsForValue().get(IOT_PROJECT_LIST);

        //返回产品列表
        return JSONUtil.toList(productListStr, ProductVo.class);

    }

    /**
     * 注册设备
     *
     * @param deviceDto 设备信息
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void registerDevice(DeviceDto deviceDto) {
        //判断设配名称是否重复
        LambdaQueryWrapper<Device> queryWrapper = Wrappers.<Device>lambdaQuery().eq(Device::getDeviceName, deviceDto.getDeviceName());
        long count = count(queryWrapper);
        if (count > 0) {
            throw new BaseException("设备名称已存在，请重新输入");
        }

        //保存设备到IOT平台
        RegisterDeviceRequest request = deviceDto.getRegisterDeviceRequest();
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        RegisterDeviceResponse response;
        try {
            response = client.registerDevice(request);
        } catch (Exception e) {
            throw new BaseException("物联网接口 - 注册设备,调用失败");
        }

        //判断设备是否保存到IOT平台
        if (!response.getBody().success) {
            throw new RuntimeException(response.getBody().getErrorMessage());
        }

        //查询产品数据
        QueryProductRequest productRequest = new QueryProductRequest();
        productRequest.setProductKey(deviceDto.getProductKey());
        productRequest.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        QueryProductResponse productResponse;
        try {
            productResponse = client.queryProduct(productRequest);
        } catch (Exception e) {
            throw new BaseException("物联网接口 - 查询产品,调用失败");
        }
        //接口是否调通
        if (!productResponse.getBody().success) {
            throw new BaseException("物联网接口 - 查询产品,调用失败");
        }

        //设备产品名称道设备对象
        Device device = BeanUtil.toBean(deviceDto, Device.class);
        device.setProductName(productResponse.getBody().getData().productName);

        //物理位置
        if (device.getLocationType().equals(0)) {
            device.setPhysicalLocationType(-1);
        }

        //补全设备id
        device.setIotId(response.getBody().getData().getIotId());

        try {
            deviceMapper.insertDevice(device);
        } catch (Exception e) {
            //删除iot设备
            DeleteDeviceRequest deleteRequest = new DeleteDeviceRequest();
            deleteRequest.setDeviceName(device.getDeviceName());
            deleteRequest.setProductKey(device.getProductKey());
            deleteRequest.setIotId(device.getIotId());
            try {
                client.deleteDevice(deleteRequest);
            } catch (Exception exception) {
                throw new BaseException("物联网接口 - 删除设备,调用失败");
            }
            throw new BaseException("该老人/位置已绑定该产品,请重新选择");
        }
    }

    /**
     * 查询设备详情
     *
     * @param deviceDto 设备信息
     * @return 设备详情
     */
    @Override
    public DeviceVo queryDeviceDetail(DeviceDto deviceDto) {
        //查询iot平台钟大哥设别数据
        QueryDeviceDetailRequest request = new QueryDeviceDetailRequest();
        request.setIotId(deviceDto.getIotId());
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        request.setProductKey(deviceDto.getProductKey());
        QueryDeviceDetailResponse response;
        try {
            response = client.queryDeviceDetail(request);
        } catch (Exception e) {
            throw new BaseException("物联网接口 - 查询设备详情,调用失败");
        }
        if (!response.getBody().success) {
            throw new BaseException("物联网接口 - 查询设备详情,调用失败");
        }

        //从数据库中查询出设备信息
        Device device = deviceMapper.selectOne(Wrappers.<Device>lambdaQuery().eq(Device::getIotId, deviceDto.getIotId()));
        DeviceVo deviceVo = BeanUtil.toBean(device, DeviceVo.class);
        //合并信息
        BeanUtil.copyProperties(response.body.getData(), deviceVo);
        return deviceVo;
    }

    /**
     * 查询物模型发布详情
     *
     * @param request 请求参数
     * @return 物模型发布详情
     */
    @Override
    public AjaxResult queryThingModelPublished(QueryThingModelPublishedRequest request) {
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        QueryThingModelPublishedResponse response;
        try {
            response = client.queryThingModelPublished(request);
        } catch (Exception e) {
            throw new BaseException("物联网接口 - 查询物模型发布详情,调用失败");
        }
        if (!response.getBody().success) {
            throw new BaseException("物联网接口 - 查询物模型发布详情,调用失败");
        }

        //返回物模型发布详情
        return AjaxResult.success(response.getBody().getData());

    }

    /**
     * 查询设备属性
     *
     * @param request 请求参数
     * @return 设备属性
     */
    @Override
    public AjaxResult queryDevicePropertyStatus(QueryDevicePropertyStatusRequest request) {
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());

        QueryDevicePropertyStatusResponse response;
        try {
            response = client.queryDevicePropertyStatus(request);
        } catch (Exception e) {
            throw new BaseException("物联网接口 - 查询设备属性,调用失败");
        }

        if (!response.getBody().success){
            throw new BaseException("物联网接口 - 查询设备属性,调用失败");
        }

        return AjaxResult.success(response.getBody().getData());
    }

    /**
     * 删除设备
     *
     * @param device 设备信息
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteDevice(Device device) {

        boolean remove = remove(Wrappers.<Device>lambdaQuery().eq(Device::getIotId, device.getIotId()));
        if (!remove) {
            throw new BaseException("删除设备失败");
        }


        DeleteDeviceRequest request = new DeleteDeviceRequest();
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        request.setIotId(device.getIotId());
        request.setProductKey(device.getProductKey());

        DeleteDeviceResponse response;
        try {
            response = client.deleteDevice(request);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        if (!response.getBody().success) {
            throw new BaseException("物联网接口 - 删除设备,调用失败");
        }

    }
}
